package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishDisableFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetMealDishMapper setMealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
//    @Autowired
//    private CategoryMapper categoryMapper;

    @Override
    @Transactional  //同时操作两张表（口味表，菜品表，保证一致性，使用事务注解）
    public void saveWithFlavour(DishDTO dishDTO) {
        //向菜品表插入一条数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insert(dish);

        //获取insert生成的主键值
        Long dishId = dish.getId();

        //向口味表插入n条数据（也可能没有）
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null&&flavors.size()>0){
            flavors.forEach(dishFlavor->{
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断是否能删除菜品
        //判断当前菜品状态--起售状态不能删除
         for (Long id:ids){
             Dish dish = dishMapper.selectById(id);
             Integer status = dish.getStatus();
             if(status == StatusConstant.ENABLE){
                 log.info("该菜品：{}，处于起售状态，不能删除",dish.getName());
                 throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
             }

         }
         //若与套餐关联，不能删除
         List<Long> setMealIds = setMealDishMapper.getSetMealIdsByDishIds(ids);
         if (setMealIds != null && setMealIds.size() > 0){
             throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
         }

        //删除菜品
//        for (Long id:ids){
//            dishMapper.deleteById(id);
//            //删除菜品的口味表数据
//            dishFlavorMapper.deleteByDishId(id);
//        }

        //根据菜品集合批量删除菜品和口味
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);

    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        Dish dish = dishMapper.selectById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);//注意categoryName和List<DishFlavor> flavors还未赋值
        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(id);
        //暂时没有用到categoryName回显，暂时注释掉
        //String categoryName = categoryMapper.getCategoryName(dish.getCategoryId());//在此处填入categoryId
        //dishVO.setCategoryName(categoryName);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        //先修改菜品的基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);

        /*
        更新口味表数据
        先删除全部原有数据，然后将当前口味数据提交插入
         */
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null&&flavors.size()>0){
            flavors.forEach(dishFlavor->{
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        Dish dish = Dish.builder().categoryId(categoryId).status(StatusConstant.ENABLE).build();
        List<Dish> dishes = dishMapper.list(dish);
        return dishes;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    //实现菜品的启用禁用功能
    public void startOrStop(Integer status, Long id) {
        /*
        在dish要被禁用时，应该判断是否处于套餐中
        如果处于套餐中，且套餐在起售状态，不允许禁用菜品
         */
        Dish dish = dishMapper.selectById(id);
        Long setMealId = setMealDishMapper.getSetMealIdByDishId(id);
        Setmeal setmeal = setmealMapper.selectById(setMealId);
        Integer setmealStatus = setmeal.getStatus();
        Integer dishStatus = dish.getStatus();

        Boolean c1 = (setmealStatus == StatusConstant.ENABLE);
        Boolean c2 = (dishStatus == StatusConstant.ENABLE);
        if (c1&&c2) {//只有在套餐启用，菜品从启用变成禁用时，抛出error message，其余情况都可以成功修改菜品状态
            throw new DishDisableFailedException(MessageConstant.DISH_CANNOT_BE_BANNED);
        }

        dishMapper.startOrStop(status,id);
    }
}
